package org.sith.taskrunner.ejb.db.dao;

import org.sith.taskrunner.ejb.db.entity.DBEntity;

import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import java.util.List;

public abstract class AbstractDAO<T extends DBEntity> implements DefaultDAO<T> {

    @PersistenceContext(unitName = "taskrunner_app")
    protected EntityManager persistenceContext;

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @Override
    public T findById(Long id) {
        return persistenceContext.find(getEnityClass(), id);
    }

    protected abstract Class<T> getEnityClass();

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @Override
    public void removeById(Long id) {
        T entity = findById(id);
        persistenceContext.remove(entity);
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @Override
    public T saveOrUpdate(T t) {
        return persistenceContext.merge(t);
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @Override
    public List<T> findAll() {
        return persistenceContext.createQuery("from " + getEnityClass().getCanonicalName()).getResultList();
    }




}
